package com.dfdchem.imd.kaiwu.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.MainActivity;
import com.dfdchem.imd.kaiwu.activity.base.BaseFragment;
import com.dfdchem.imd.kaiwu.adapter.HomeBannerAdapter;
import com.dfdchem.imd.kaiwu.adapter.HomeGridAdapter;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.manager.GlideManager;
import com.dfdchem.imd.kaiwu.manager.PermissionManager;
import com.dfdchem.imd.kaiwu.model.BannerBean;
import com.dfdchem.imd.kaiwu.model.Module;
import com.dfdchem.imd.kaiwu.model.RespList;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.dfdchem.imd.kaiwu.util.SPUtil;
import com.dfdchem.imd.kaiwu.util.StringUtil;
import com.king.zxing.CaptureActivity;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import pub.devrel.easypermissions.EasyPermissions;

public class HomeFragment extends BaseFragment implements OnHttpResponseListener, View.OnClickListener, OnBannerListener<BannerBean>, OnRefreshListener, AdapterView.OnItemClickListener {
    private static final String TAG = "HomeFragment";

    private MainActivity mainActivity;

    private ImageView avatar;
    private ImageView qr_code_scan;
    private RelativeLayout home_search_layout;
    private TextView home_search_hint;

    private RefreshLayout refreshLayout;

    private Banner<BannerBean, HomeBannerAdapter> banner;
    private HomeBannerAdapter bannerAdapter;

    private GridView gridView;
    private HomeGridAdapter homeGridAdapter;

    private SPUtil spUtil;

    private static final int request_code_get_banner = 1;
    private static final int request_code_get_module = 2;

    private boolean isBannerRefresh = false;
    private boolean isModuleRefresh = false;

    private static final String SPUtil_Banner = "SPUtil_Banner";
    private static final String SPUtil_Module = "SPUtil_Module";

    private static final String[] hints = {
            "MES系统上线",
            "九大指标检查通报",
            "智慧园区二期启动会顺利召开",
            "热烈欢迎中站区领导莅临多氟多指导检查",
            "关于组织参加焦作市第十届职业技能大赛的通知"
    };

    private Timer timer;

    public HomeFragment() {
        super();
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.fragment_home,
                container, false);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 初始化MainActivity
        if (getActivity() instanceof MainActivity) {
            mainActivity = (MainActivity) getActivity();
        }

        spUtil = new SPUtil(getActivity());
        initData();
        initEvent();
    }


    private void initView(View view) {
        avatar = view.findViewById(R.id.avatar);

        home_search_layout = view.findViewById(R.id.home_search_layout);
        home_search_hint = view.findViewById(R.id.home_search_hint);

        qr_code_scan = view.findViewById(R.id.qr_code_scan);

        refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);

        banner = view.findViewById(R.id.home_banner);
        bannerAdapter = new HomeBannerAdapter(getActivity(), null);
        banner.setAdapter(bannerAdapter)
                .setIndicator(new CircleIndicator(getActivity()))
                .setOnBannerListener(this);

        gridView = view.findViewById(R.id.home_grid);
        homeGridAdapter = new HomeGridAdapter(getActivity());
        gridView.setAdapter(homeGridAdapter);

    }

    private void initData() {
        // 先从本地读取数据
        User user = DataManager.getInstance().getUser();
        if (user != null) {
            String avatar_url = user.getAvatar();
            if (!StringUtil.isEmpty(avatar_url)) {
                new GlideManager(this).load(avatar, avatar_url, RequestOptions.bitmapTransform(new RoundedCorners(20)));
            }
        }

        List<BannerBean> bannerList = spUtil.getList(SPUtil_Banner, BannerBean.class);
        Log.d(TAG, " bannerList:" + bannerList);
        if (bannerList != null) {
            banner.setDatas(bannerList);
        }

        List<Module> moduleList = spUtil.getList(SPUtil_Module, Module.class);
        Log.d(TAG, " moduleList:" + moduleList);


        if (moduleList != null) {
            homeGridAdapter.setModules(moduleList);
        }

        refreshData();

        // 搜索框内容定时更新
        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                String string = hints[msg.getData().getInt("index")];

                if (getActivity() != null && getActivity().getResources() != null) {
                    home_search_hint.setText(string);
                    if (string.length() >= 15) {
                        home_search_hint.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                                getActivity().getResources().getDimension(R.dimen.text_size_micro));
                    } else {
                        home_search_hint.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.text_size_small));
                    }
                }

                super.handleMessage(msg);
            }
        };

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                int hitIndex = (int) (new Date().getTime() / 1000 / 3 % hints.length);
                Log.d(TAG, hitIndex + "");
                Bundle bundle = new Bundle();
                bundle.putInt("index", hitIndex);
                Message message = new Message();
                message.setData(bundle);
                handler.sendMessage(message);
            }
        };

        timer = new Timer();
        timer.schedule(task, 0, 3000);

    }

    private void initEvent() {
        avatar.setOnClickListener(this);
        home_search_layout.setOnClickListener(this);
        qr_code_scan.setOnClickListener(this);
        banner.setOnBannerListener(this);
        refreshLayout.setOnRefreshListener(this);
        gridView.setOnItemClickListener(this);
    }

    private void refreshData(){
        isBannerRefresh = true;
        isModuleRefresh = true;
        mainActivity.runThread(TAG + "modules", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getBanner(request_code_get_banner, HomeFragment.this);
            }
        });

        // 更新本地存储的用户信息
        mainActivity.runThread(TAG + "getModule", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getModule(request_code_get_module, HomeFragment.this);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.avatar:
                mainActivity.setSelect(3);
                break;
            case R.id.home_search_layout:
                mainActivity.toActivity(RouterPath.SEARCH_ACTIVITY);
                break;
            case R.id.qr_code_scan:
                // Intent intent = new Intent(getActivity(), CaptureActivity.class);
                // mainActivity.startActivity(intent);
                if (android.os.Build.VERSION.SDK_INT >=  Build.VERSION_CODES.M) {
                    if (!EasyPermissions.hasPermissions(getActivity(), PermissionManager.PERMISSION_CAMERA)) {
                        EasyPermissions.requestPermissions(this, getString(R.string.text_permission_file), PermissionManager.REQUEST_PERMISSION_CAMERA, PermissionManager.PERMISSION_CAMERA);
                    } else {
                        Intent intent = new Intent(getActivity(), CaptureActivity.class);
                        getActivity().startActivityForResult(intent, MainActivity.request_code_qr_scan);
                    }
                }
                break;
        }

    }

    @Override
    public void onDestroy() {
        timer.cancel();
        timer = null;
        super.onDestroy();
    }

    @Override
    public void OnBannerClick(BannerBean data, int position) {
        if (!StringUtil.isEmpty(data.getUrl())) {
            if (!StringUtil.isEmpty(data.getUrl())) {
                Uri uri = Uri.parse(data.getUrl());
                mainActivity.handleScheme(uri);
            }
        }
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        if (e != null) {
            isBannerRefresh = false;
            if (!isModuleRefresh) {
                refreshLayout.finishRefresh();
            }
            Toast.makeText(mainActivity, "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }

        switch (requestCode) {
            case request_code_get_banner:
                isBannerRefresh = false;
                if (!isModuleRefresh) {
                    refreshLayout.finishRefresh();
                }
                RespList<BannerBean> resp = JSON.parseRespList(resultJson, BannerBean.class);
                if (resp == null || resp.getCode() != 200) {
                    Toast.makeText(getActivity(), resp != null ? resp.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<BannerBean> banners = resp.getData();

                if (banners == null) {
                    Toast.makeText(getActivity(), "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }

                if (banners.size() > 0) {
                    spUtil.putObject(SPUtil_Banner, banners);
                    bannerAdapter.setDatas(banners);
                }

                break;

            case request_code_get_module:
                isModuleRefresh = false;
                if (!isBannerRefresh) {
                    refreshLayout.finishRefresh();
                }
                RespList<Module> resp1 = JSON.parseRespList(resultJson, Module.class);
                if (resp1 == null || resp1.getCode() != 200) {
                    Toast.makeText(getActivity(), resp1 != null ? resp1.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<Module> modules = resp1.getData();
                if (modules == null) {
                    Toast.makeText(getActivity(), "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }
                if (modules.size() > 0) {
                    spUtil.putObject(SPUtil_Module, modules);
                }
                homeGridAdapter.setModules(modules);
                homeGridAdapter.notifyDataSetChanged();
                break;

        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object obj = parent.getItemAtPosition(position);
        if (obj instanceof Module) {
            Module module = (Module) obj;
            if (!StringUtil.isEmpty(module.getUrl())) {
                Uri uri = Uri.parse(module.getUrl());
                mainActivity.handleScheme(uri);
            }
        }
    }
}
